package org.apache.jmeter.functions;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;

/**
 * 参数 SHA1加密
 * @author 刘德龙
 *
 */
public class ParamSHA1 extends AbstractFunction {

	private static final Logger log = LoggingManager.getLoggerForClass();

    private static final List<String> desc = new LinkedList<>();

    private static final String KEY = "__paramSHA1"; //$NON-NLS-1$

    static {
        desc.add("paramSHA1_string"); //$NON-NLS-1$
    }

    private Object[] values;

    public ParamSHA1() {
    }


    public static String sha1(String text) {
		MessageDigest md = null;
		String outStr = null;
		try {
			md = MessageDigest.getInstance("SHA-1");
			byte[] digest = md.digest(text.getBytes("UTF-8"));
			outStr = byteToString(digest);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return outStr.toUpperCase();
	}

	private static String byteToString(byte[] digest) {
		StringBuilder buf = new StringBuilder();
		for (int i = 0; i < digest.length; i++) {
			String tempStr = Integer.toHexString(digest[i] & 0xff);
			if (tempStr.length() == 1) {
				buf.append("0").append(tempStr);
			} else {
				buf.append(tempStr);
			}
		}
		return buf.toString().toLowerCase();
	}

    /** {@inheritDoc} */
    @Override
    public String execute(SampleResult previousResult, Sampler currentSampler)
            throws InvalidVariableException {
        String decodeString = ""; //$NON-NLS-1$
        String rawString = ((CompoundVariable) values[0]).execute();
        log.info("-------source String="+rawString);
        System.out.println(rawString);
        decodeString = sha1(rawString);
        System.out.println(decodeString);
        log.info("-------encypt String="+decodeString);
        return decodeString;
    }

    /** {@inheritDoc} */
    @Override
    public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
        checkParameterCount(parameters, 1);
        values = parameters.toArray();
    }

    /** {@inheritDoc} */
    @Override
    public String getReferenceKey() {
        return KEY;
    }

    /** {@inheritDoc} */
    @Override
    public List<String> getArgumentDesc() {
        return desc;
    }


    public static void main(String[] args){
    	System.out.println(sha1("d5d907738f444eccb9e26c1e9f9bf295appcode100094brandname0carNumber100construct0deliveryfee12340000deliveryratio100depositfee0depositratio0dispatchdate1491375912054emptyMargin0formatjsonfreightKind2freightRates12340000haulageoperatorcodeno123456haulageoperatormoney190000haulageoperatorname爱物流承运公司haulageoperatorstate1informationFees0isToAllGroupfalseisToAllUserfalselaterpaystate0length0loadpayEtcFee0loadpayEtcRatio0loadpayMoneyFee0loadpayMonyeRatio0loadpayfee0loadpayratio0methodstock.publishneedReturnfalseopenEmptyfalseopenFeesfalseopenFreighttrueopenabletrueplatecolor0price1234.0元session610d70f7656049ce9c0925e0486c4b08sourceAddressCodesaec98df96e224c17b195e87748b66cd2sourcecode420100sourcelat0.0sourcelon0.0sourcename武汉special0state0stockdesc再等等6stockkind1stocktype2targetAddressCodes291e7b6ca43e46cdb300d5f2edbf00fftargetcode420100targetlat0.0targetlon0.0targetname武汉transitTime0unit55吨userissb0v2.0d5d907738f444eccb9e26c1e9f9bf295"));
    }
}
